
# PROJECT WIDOW Shotgun / Blender Python API Experiments
# ---------------------------------------------------------------------------------------------
# Widow Shotgun Connection
# ---------------------------------------------------------------------------------------------
#	
#	
#	
# ---------------------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------------------
# Imports
# ---------------------------------------------------------------------------------------------

import os
import sys
import urllib
from time import sleep
import time
from shotgun_api3 import Shotgun # Shotgun API 3
from pprint import pprint # useful for debugging

# ---------------------------------------------------------------------------------------------
# Begin
# ---------------------------------------------------------------------------------------------

print "Starting Shotgun Event Viewer ...\n"

# ---------------------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------------------
# Globals
# ---------------------------------------------------------------------------------------------

DEFAULT_SHOTGUN_API = "/usr/lib/python2.5/site-packages/shotgun_api3.py" # Place this in your Pyshared directory
VERSION = '0.3'


# ---------------------------------------------------------------------------------------------
# TESTING Globals - comment out for production use
# ---------------------------------------------------------------------------------------------

SERVER_PATH = "https://yourshotgunsite.shotgunstudio.com"
SCRIPT_NAME = "event_veiwer_0_3"
SCRIPT_KEY = 'shotgungeneratedkey' # Script key number

# ---------------------------------------------------------------------------------------------
# Project Id's - Includes production and testing project id settings, comment out prefered id
# ---------------------------------------------------------------------------------------------

# Project ID
PROJECT = {'type':'Project', 'id':64}


# ---------------------------------------------------------------------------------------------
# Main 
# ---------------------------------------------------------------------------------------------

print "Shotgun API script "+SCRIPT_NAME+" "+VERSION+""
print "Connecting to %s..." % (SERVER_PATH),
sg = Shotgun(SERVER_PATH, SCRIPT_NAME, SCRIPT_KEY)
print "\nConnected"

# ---------------------------------------------------------------------------------------------
# Connect to Shotgun - Function to connect to a Shotgun server
# ---------------------------------------------------------------------------------------------

def shotgunConnect():
    from shotgun_api3 import Shotgun
    #sg = Shotgun(SERVER_PATH, SCRIPT_NAME, SCRIPT_KEY)
    return sg
    


#if __name__ == '__main__':



# ---------------------------------------------------------------------------------------------
# Testing Block BEGIN - Use this to test script code.
# ---------------------------------------------------------------------------------------------
print "Sending request to Shotgun ...\n"
#result = sg.schema_entity_read()
sg.find("Project",filters=[],fields=['name'])
print "Recieved ... :)"
#pprint(result)
def log(msg):
    print time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()) +": "+msg

# ---------------------------------------------------------------------------------------------
# Main 
# ---------------------------------------------------------------------------------------------
if __name__ == '__main__':    

    sg = Shotgun(SERVER_PATH, SCRIPT_NAME, SCRIPT_KEY)

    # ---------------------------------------------------------------------------------------------
    # get the id of the latest EventLogEntry
    # ---------------------------------------------------------------------------------------------
    result = sg.find_one("EventLogEntry",filters=[], fields=['id'], order=[{'column':'created_at','direction':'desc'}])    
    current = result['id']
    log('beginning processing starting at event #%d' % current)

    # ---------------------------------------------------------------------------------------------
    # find all Events since the last check
    # ---------------------------------------------------------------------------------------------
    while True:
        for event in sg.find("EventLogEntry",filters=[['id', 'greater_than', current]], fields=['id','event_type','attribute_name','meta','entity'], 
                                order=[{'column':'created_at','direction':'asc'}], filter_operator='all'):
            log('processing event id %d' % event['id'])

            # check if we care about the event
            if event['event_type'] == 'Shotgun_Task_Change' and event['attribute_name'] == 'sg_status_list':

                # Task status isn't 'final' so disregard...
                if event['meta']['new_value'] != 'fin':
                    continue

                # Load up the Task so we can check if we care about it
                task = sg.find_one("Task",filters=[['id', 'is', event['entity']['id']]], fields=['id','entity','content'])

                # Task is a Layout task for a Shot. 
                if task['entity'] and task['entity']['type'] == 'Shot' and task['content'] == 'Layout':
                     # find an animation task for the same Shot
                     task_filters = [
                         ['entity', 'is', {'type':'Shot','id':task['entity']['id']} ],
                         ['content', 'is', 'Animation']
                         ]
                     animation_task = sg.find_one("Task",filters=task_filters, fields=['id','sg_status_list'])

                     # update it to 'rdy' if it's currently 'wtg'
                     if animation_task['sg_status_list'] == 'wtg':
                         sg.update("Task",entity_id=animation_task['id'], data={'sg_status_list' : 'rdy'})
                         log("updated animation task on %s %s to rdy" % 
                                (task['entity']['type'],task['entity']['name']))
        try:
            current = event['id']
        except NameError, e:
            pass
        sleep(1)
# ---------------------------------------------------------------------------------------------
# Testing Block END
# ---------------------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------------------
# END
# ---------------------------------------------------------------------------------------------

print "Shotgun API script "+SCRIPT_NAME+" "+VERSION+" comm with "+SERVER_PATH+" ... completed\n"
